import { Component } from "react";

import { SearchBar } from "antd-mobile";

import styles from "./index.module.css";
import { API } from "../../../utils/api";

export default class RentSearch extends Component {
  // 定时器id
  timer = null

  state = {
    // 搜索关键词
    searchText: '',
    // 检索结果列表
    tipsList: []
  }

  onChange = (val) => {
    const id = JSON.parse(localStorage.getItem('hkzf_city'))['value']
    if (!val) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      return this.setState({
        searchText: '',
        tipsList: []
      })
    } else {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(async () => {
        let res = await API('/area/community', {
          params: {
            name: val,
            id: id
          }
        })
        const {status, data} = res
        if (status === 200) {
          this.setState({
            searchText: val,
            tipsList: data.body
          })
        }
      }, 500)
    }
  }

  renderTips = () => {
    const { tipsList } = this.state
    return (
      tipsList.map(item => {
        return <li key={item.community} className={styles.tip} onClick={() => {this.onTipsClick(item)}}>
          {item.communityName}
        </li>
      })
    )
  }

  onTipsClick = (item) => {
    this.props.history.replace('/rent/add', {
      name: item.communityName,
      id: item.community
    })
  }

  render() {
    return (
      <div className={styles.rentSearch}>
        <SearchBar
          placeholder="输入小区或地址"
          ref={ref => this.manualFocusInst = ref}
          onChange={this.onChange}
        />
        {
          this.renderTips()
        }
      </div>
    )
  }
}